package com.jzr.medical.controller.api;

import com.jzr.common.util.UrlUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/mediaFile")
public class MediaFileController {
    @Value("${file.mediaFile-upload-folder}")
    private String uploadFolder;

    @Value("${file.mediaFile-download-url}")
    private String downloadUrl;


    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        try {
            if(file == null || file.isEmpty()){
                throw new Exception("上传文件不能为空");
            }
            String fileName = file.getOriginalFilename();

            File fullPath = new File(uploadFolder);
            if (!fullPath.exists()) {
                throw new Exception("文件夹不存在," + fullPath.getAbsolutePath());
            }

            File dest = new File(fullPath, fileName);
            if(dest.exists()){
                dest.delete();
            }
            file.transferTo(dest);
            resultMap.put("location", UrlUtil.concat(downloadUrl,fileName));
        }catch (IOException e){
            e.printStackTrace();
            throw new Exception("保存文件失败");
        }
        return resultMap;
    }
}
